/**
 * created by dqn 2018/3/13 16:58
 */

package main.controller.pages;

import main.entity.Song;
import main.entity.WebUser;
import main.service.SongService;
import main.service.WebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class PlayPage {
    final String currentSong = "currentSong";
    @Autowired
    SongService songService;
    @Autowired
    WebUserService webUserService;

    @RequestMapping(value = "/play",method = RequestMethod.GET)
    public String playerPage(HttpSession httpSession, HttpServletRequest httpServletRequest){
        String pk = httpServletRequest.getParameter("id");
        httpSession.setAttribute(currentSong,pk);
        new Thread(()->{
            /**
             * 歌曲点击量加一
             */
            Song song = songService.getSongById(Integer.valueOf(pk));
            song.setClick(song.getClick()+1);
            songService.updateSong(song);

            /**
             * 每听一首歌积分加 1
             */
            WebUser webUser = (WebUser) httpSession.getAttribute("user");
            if (webUser!=null){
                webUser.setPoints(webUser.getPoints()+1);
                webUserService.updateUser(webUser);
            }
        }).start();
        return "play";
    }

    @RequestMapping(value = "/song/current/id",method = RequestMethod.GET)
    @ResponseBody
    public String getCurrentMusicId(HttpSession httpSession){
        String id = (String) httpSession.getAttribute(currentSong);
        return id;
    }

    @RequestMapping(value = "/song/current/id/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String setId(@PathVariable String id,HttpSession httpSession){
        httpSession.setAttribute(currentSong,id);
        return "";
    }
}
